package cn.com.gzheroli.bfw.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.gzheroli.auth.service.TSDataruleService;
import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.core.common.mapper.DepartMapper;
import cn.com.gzheroli.core.common.mapper.UserMapper;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.LogUtil;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.core.util.mybatis.SqlMapper;
import cn.com.gzheroli.rabbitmq.service.log.LogService;
import cn.com.gzheroli.service.bfw.DepartService;


@Service("departService")
public class DepartServiceImpl  implements
		DepartService {
	@Resource
	private DepartMapper departMapper;
	@Resource
	private SystemService systemService;
	@Resource
	private CommonService commonService;
	@Resource
	private UserMapper userMapper;
	@Autowired
	private LogService logService;
	@Autowired
	  private TSDataruleService dataruleService;
	@Autowired
	SqlMapper sqlMapper;
	public List<TSUser> getTsUserByDepartId(String departId) {
		Map para=new HashMap();
		String sql=new SQL(){{
			SELECT("bu.*,u.*");
			FROM("T_S_BASE_USER bu");
		    FROM("");
		    INNER_JOIN("T_S_USER u on bu.ID=u.ID and bu.STATUS='1'");
		    WHERE("bu.DEPART_ID=#{departId}");
	    }}.toString();
		//para.put("sql", sql);
		para.put("departId", departId);
		//List<TSUser> users=userMapper.selectListBySql(para);
		List<TSUser> users=sqlMapper.selectList(sql, para, TSUser.class);
		return users;
	}
	public List<Map<String,Object>> getDepartList(Map dataMap) {
		
		return  departMapper.getDepartList(dataMap);
	}

	public List<Map<String,Object>> getUserListByDepartId(Map dataMap) {
		/*Map dataMap =new HashMap();
		Integer page = Integer.valueOf(Integer.parseInt(request.getParameter("page")));
	    Integer rows = Integer.valueOf(Integer.parseInt(request.getParameter("rows")));
	    Integer start = Integer.valueOf((page.intValue() - 1) * rows.intValue())+1;
	    Integer end = Integer.valueOf(page.intValue() * rows.intValue() );
	    dataMap.put("maxResults", end.intValue());
	    dataMap.put("firstResult", start.intValue());
		dataMap.put("departid", request.getParameter("departid"));*/
	
		return departMapper.getUserListByDepartId(dataMap);
	}
	
	public List getAllSubDeptIds(String deptId,List deptIds){ 
		deptIds.add(deptId);
		String sql="select ID from T_S_DEPART where STATUS='1' and PARENT_ID=#{parentId}";
		//List<Map<String, Object>>  deptList=jdbcDao.findForJdbc(sql, deptId);
		Map para=new HashMap();
		para.put("parentId", deptId);
		List<Map<String, Object>>  deptList=commonService.findForJdbc(sql, para);
		if(deptList!=null&&!deptList.isEmpty()){
			for(Map<String, Object> dept:deptList){
				if(!deptIds.contains(dept.get("id").toString()))
				deptIds.add(dept.get("id").toString());
				getSubDeptIds(dept.get("id").toString(),deptIds);
				/*if(subDepts.startsWith(","))
				deptIds=deptIds+subDepts;*/
			}
		}
		return deptIds;		
	}
	
	public List getSubDeptIds(String deptId,List deptIds){ 
		String sql="select ID from T_S_DEPART where STATUS='1' and PARENT_ID=#{parentId}";
		//List<Map<String, Object>>  deptList=jdbcDao.findForJdbc(sql, deptId);
		Map para=new HashMap();
		para.put("parentId", deptId);
		List<Map<String, Object>>  deptList=commonService.findForJdbc(sql, para);
		if(deptList!=null&&!deptList.isEmpty()){
			for(Map<String, Object> dept:deptList){
				if(!deptIds.contains(dept.get("id").toString()))
					deptIds.add(dept.get("id").toString());
				 getSubDeptIds(dept.get("id").toString(),deptIds);
				/*if(subDepts.startsWith(","))
				deptIds=deptIds+subDepts;*/
			}
		}
		return deptIds;		
	}
	
	public TSDepart getDepart(String id){
		/*SQL sql=new SQL();
		sql.SELECT("d.*,(select d2.DEPART_NAME from T_S_DEPART d2 where d.PARENT_ID=d2.id) PARENT_NAME");
		sql.FROM("T_S_DEPART d");*/
		String sql="select d.*,(select d2.DEPART_NAME from T_S_DEPART d2 where d.PARENT_ID=d2.id) PARENT_NAME";
		sql=sql+" from T_S_DEPART d where d.ID=#{id}";
		Map para=new HashMap();
		para.put("id", id);
		//return commonService.findOneObjForJdbc(sql, para, TSDepart.class);
		//return commonService.getEntity(sql, TSDepart.class, id);
		return sqlMapper.selectOne(sql, para, TSDepart.class);
	}
	
	public  void updateDeptLevelNoCased(String pid,String plevelNo) {
		Map para=new HashMap();
		para.put("pid", pid);
		/*SQL sql=new SQL();
		sql.SELECT("*");
		sql.FROM("T_S_DEPART");*/
		String sql="select * from T_S_DEPART where 1=1 ";
		if(pid==null||pid.trim().equals(""))
			sql=sql+" and (PARENT_ID is null or PARENT_ID='')";
		else
			sql=sql+" and PARENT_ID=#{pid}";
		List<TSDepart> depts=commonService.findByQueryString(sql, TSDepart.class, para);
		for(int i=0;i<depts.size();i++){
			TSDepart depart=depts.get(i);
			DecimalFormat df = new DecimalFormat("000");
			String newLevelNo=plevelNo+df.format(i+1);
			depart.setLevelNo(newLevelNo);
			commonService.executeSQL("update T_S_DEPART set LEVEL_NO='"+newLevelNo+"' where ID='"+depart.getId()+"'");
			updateDeptLevelNoCased(depart.getId(),newLevelNo);
		}
		
    }
public List<ComboTree> setPFunction(TSUser user,String parentid,String selfId){
	String sql="select ID,DEPARTMENT_CODE,PARENT_ID,DEPART_NAME from T_S_DEPART d where d.status='1'";
	if(!parentid.equals(""))
		sql=sql+" and PARENT_ID='"+ parentid+"'";
	else
		sql=sql+" and (PARENT_ID='' or PARENT_ID is null)";
	if(null != selfId){
		sql=sql+" and id='"+ selfId+"'";
	}
	Map dataMap=new HashMap();
	//String authSql=dataruleService.genSqlByModuleName("authDepartSql","d",user);	
	//sql=sql+" "+authSql;
	List<Map<String, Object>> deptList=commonService.findForJdbc(sql,dataMap);
	List<ComboTree> comboTrees = new ArrayList<ComboTree>();
	for(Map dep:deptList){
		ComboTree treebean = new ComboTree();
		treebean.setText(dep.get("departName").toString());
		treebean.setId(dep.get("id").toString());
		Long subDeptCount=commonService.getCountForJdbc("select count(*) from T_S_DEPART t where t.PARENT_ID='"+dep.get("id").toString()+"' and t.STATUS='1'");
		if(subDeptCount>0)
			treebean.setState("closed");
		else
			treebean.setState("open");
		comboTrees.add(treebean);
    }
	return comboTrees;
}
public AjaxJson saveDepart(TSDepart depart,String pid,Map logMap){
	String message="";
	AjaxJson j = new AjaxJson();
	if (StringUtil.isNotEmpty(depart.getId())) {
		message = "部门: " + depart.getDepartName() + "被更新成功";
		TSDepart olddepart=commonService.getEntity(TSDepart.class, depart.getId());
		if(!olddepart.getParentId().equals(depart.getParentId())||depart.getLevelNo()==null||depart.getLevelNo().trim().equals("")){
			TSDepart pdepart=commonService.getEntity(TSDepart.class, pid);
			String sql="select LEVEL_NO  from T_S_DEPART where PARENT_ID=#{pid}  and LEVEL_NO is not null order by LEVEL_NO desc";
			Map para=new HashMap();
			para.put("pid", pid);
			Map map=commonService.findOneForJdbc(sql,para );
			String pLevelNo=pdepart.getLevelNo()==null?"":pdepart.getLevelNo();
			String levelNo=map==null||map.get("levelNo")==null?pLevelNo+"000":(String)map.get("levelNo");
			String newLevelNo=StringUtil.fillDepartLevel(pLevelNo,levelNo);
			depart.setLevelNo(newLevelNo);
		}
		commonService.update(depart);
		logService.addLogRoleauth(message, Globals.Log_Type_UPDATE, null,logMap);
	} else {
		TSDepart pdepart=commonService.getEntity(TSDepart.class, pid);
		String sql="select LEVEL_NO  from T_S_DEPART where PARENT_ID=#{pid}  and LEVEL_NO is not null  order by LEVEL_NO desc";
		Map para=new HashMap();
		para.put("pid", pid);
		Map map=commonService.findOneForJdbc(sql,para );
		String pLevelNo=pdepart.getLevelNo()==null?"":pdepart.getLevelNo();
		String levelNo=map==null||map.get("levelNo")==null?pLevelNo+"000":(String)map.get("levelNo");
		String newLevelNo=StringUtil.fillDepartLevel(pLevelNo,levelNo);
		depart.setLevelNo(newLevelNo);
		depart.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
		message = "部门: " + depart.getDepartName() + "被添加成功";
		commonService.save(depart);
		logService.addLogRoleauth(message, Globals.Log_Type_INSERT,null, logMap);
	}
	j.setMsg(message);
	j.setSuccess(true);
	return j;
}
/**
 * 
* @Title: delDepartCase 
* @Description: 级联删除部门及修改用户部门 
* @param @param id    设定文件 
* @return void    返回类型 
* @throws
 */
public void delDepartCase(String id){
	String sql="";
	List<TSDepart> deptList=commonService.findByProperty(TSDepart.class, "parentId", id);
	if(deptList==null||deptList.isEmpty()){
		String updateSql="update T_S_BASE_USER set DEPART_ID='' where DEPART_ID=#{departId}";
		Map deptParam=new HashMap();
		deptParam.put("departId", id);
		commonService.updateMapper(updateSql, deptParam);
		commonService.delete(TSDepart.class, id);
		return;
	}else{
		for(TSDepart dept:deptList){
			delDepartCase(dept.getId());
		}
	}
	
}
}
